#include "file_backend.h"

namespace sfc::log {

FileBackend::FileBackend(fs::File file) : _file{mem::move(file)} {}

FileBackend::FileBackend(FileBackend&&) noexcept = default;

FileBackend::~FileBackend() {}

auto FileBackend::create(fs::Path path) -> io::Result<FileBackend> {
  auto opts = fs::OpenOptions{};
  opts._append = true;
  opts._write = true;
  opts._create = true;

  auto file = opts.open(path);
  if (file.is_err()) {
    return mem::move(file).get_err_unchecked();
  }
  return FileBackend{mem::move(file).unwrap()};
}

void FileBackend::flush() {}

void FileBackend::write_entry(Entry entry) {
  static const Str LEVEL_STR[] = {"VB", "DE", "II ", "WW ", "EE", "FA", "??"};

  static thread_local auto buf = String{};
  buf.clear();
  fmt::write(buf, "{} [{}] {}\n", entry.time, LEVEL_STR[(u32)entry.level], entry.msg);

  _file.write_str(buf.as_str());
}

}  // namespace sfc::log
